// ==UserScript==
// @name         zentao.git
// @namespace    http://tampermonkey.net/
// @icon         https://myjob.zjshenyue.cn/zentao/favicon.ico
// @version      1.0.5
// @description  自用禅道扩展脚本!
// @author       wongchance
// @match        http://myjob.zjshenyue.cn/*
// @match        https://myjob.zjshenyue.cn/*
// @match        http://www.zjshenyue.cn:83/*
// @match        http://192.168.0.207:83/*
// @updateURL    https://gitee.com/wongchance/jscollection/raw/master/zentao.user.js
// @downloadURL  https://gitee.com/wongchance/jscollection/raw/master/zentao.user.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/echarts/4.3.0/echarts.min.js
// @grant        none
// ==/UserScript==

/*
v0.2 2023/10
- fix 增加创建任务+完成任务快捷输入

v0.3 2024/4
- feat 禅道增加迭代名词过滤

v0.4.3 2024/5
- feat 增加过滤后的简单统计

v0.5.0 2024/5/20
- feat 增加解决bug的bug原因表单项

v0.6.3 2024/5/21
- feat 增加bug原因的chart 统计
- feat 增加all和按搜索
- feat chart图增加value
- feat 增加checkbox并添加到localstorage

v0.7 2024/6/19
- feat 增加bug 跳转和 task 跳转

v0.7.1 2024/7/17
- feat 延时读取任务完成，增加加载速度

v0.8 2024/8/9
- feat bug原因取最新的，而不是写死
- feat 增加默认组织的设定功能，在/zentao/report-worksummary.html 任务完成表页面设定，同时调整部分按钮和输入框ui

v0.8.1 2024/8/10
- feat bug原因控制限制
- fix 修复过滤迭代以后没有超链
- fix url.indexOf .toLowerCase()

v0.9 2024/9/24
- feat 增加按产品过滤迭代，加统计 /zentao/report-projectdeviation.html

v0.9.1 2024/9/25
- feat 增加按迭代生命周期

v0.9.2 2024/9/27
- feat /zentao/report-projectdeviation.html 
- 项目字样修改为迭代
- 初始化进入时进行统计
- 尝试设置默认分页每页 2000

v1.0.1 2024/10/9
- 完成任务时填写时间 
- bug统计条数
- 更换cdn

v1.0.3 2024/10/10
- 客户问题 列表文字
- 迭代偏差报表过滤项

v1.0.4 2024/10/11
- 迭代偏差报表过滤项修复前两个合并为空导致的问题
- 修复增加了列导致的统计值问题

*/

// 组织代码,0为全部部门
// 开发二组为3
// 其他自寻
var organizeCode = '0'

;(function () {
  function defaultOrgfn() {
    //https://myjob.zjshenyue.cn/zentao/report-worksummary-20240802-20240809-0.html
    let urlOrgCode = location.href.split('-')[4].replace('.html', '')
    localStorage.setItem('defaultOrg', urlOrgCode)
    alert('设置默认组织为：' + urlOrgCode)
  }

  function mousedownfn() {
    if (!jQuery('#os').val()) {
      alert('请先选择Bug原因')
    }
  }

  function lastweekfn() {
    var datebefore = getDayByDate(-7, jQuery('#begin').val())
    var dateafter = getDayByDate(-7, jQuery('#end').val())

    var worksummarydatestring = '-' + datebefore + '-' + dateafter + '-'
    var newhref = location.href.replace(
      '-' +
        jQuery('#begin').val().replace('-', '').replace('-', '') +
        '-' +
        jQuery('#end').val().replace('-', '').replace('-', '') +
        '-',
      worksummarydatestring
    )
    location.href = newhref
  }

  function nextweekfn() {
    var datebefore = getDayByDate(7, jQuery('#begin').val())
    var dateafter = getDayByDate(7, jQuery('#end').val())

    var worksummarydatestring = '-' + datebefore + '-' + dateafter + '-'
    var newhref = location.href.replace(
      '-' +
        jQuery('#begin').val().replace('-', '').replace('-', '') +
        '-' +
        jQuery('#end').val().replace('-', '').replace('-', '') +
        '-',
      worksummarydatestring
    )
    location.href = newhref
  }

  function appendHtmlToTabel(params) {
    console.log('params', params)
    $('#worksummary').after(
      `<table class="table table-condensed table-striped table-bordered table-fixed" id="worksummary2"><thead><tr class="colhead text-center"><th class="userWidth" title="完成者">完成者</th><th class="" title="所属迭代">所属迭代</th><th class="w-50px" title="编号">编号</th><th class="" title="任务名称">任务名称</th><th class="priWidth" title="优先级">优先级</th><th class="w-80px" title="预计开始">预计开始</th><th class="w-80px" title="实际开始">实际开始</th><th class="w-80px" title="截止日期">截止日期</th><th class="dateWidth" title="实际完成">实际完成</th><th class="delayWidth" title="延期(天)">延期(天)</th><th class="estWidth" title="最初预计">最初预计</th><th class="taskConsumedWidth" title="任务总消耗">任务总消耗</th></tr></thead><tbody>`
    )

    let yanqi = 0
    let yuji = 0
    let xiaohao = 0
    params.forEach((item) => {
      yanqi += item['延期(天)'] ? parseFloat(item['延期(天)']) : 0
      yuji += item.最初预计 ? parseFloat(item.最初预计) : 0
      xiaohao += item.任务总消耗 ? parseFloat(item.任务总消耗) : 0
      var trHtml =
        `<tr class="text-center"><td class="w-user">` +
        item.完成者 +
        `</td><td class="text-left" title="` +
        item.所属迭代 +
        `">` +
        item.所属迭代 +
        `</td><td>` +
        item.编号 +
        `</td><td class="text-left" title="` +
        item.任务名称 +
        `">` +
        item.任务名称 +
        `</td><td>` +
        item.优先级 +
        `</td><td>` +
        item.预计开始 +
        `</td><td>` +
        item.实际开始 +
        `</td><td>` +
        item.截止日期 +
        `</td><td>` +
        item.实际完成 +
        `</td><td>` +
        (item['延期(天)'] ? item['延期(天)'] : '') +
        `</td><td>` +
        item.最初预计 +
        `</td><td>` +
        item.任务总消耗 +
        `</td></tr>`

      console.log(yanqi)
      console.log(yuji)
      console.log(xiaohao)

      $('.panel-title').html(
        '任务完成汇总表<div color="red">延期(天)->&nbsp;' +
          yanqi +
          ';&nbsp;&nbsp;最初预计->&nbsp;' +
          yuji +
          ';&nbsp;&nbsp;任务总消耗->&nbsp;' +
          xiaohao +
          ';</div>'
      )
      $('#worksummary2 tbody').append(trHtml)
    })
  }

  var tjson = []
  var tbugjson = []

  function changeDiedai() {
    console.log(jQuery('#diedaiName').val())
    $('#worksummary2').remove()
    var targetString = jQuery('#diedaiName').val()
    if (targetString) {
      $('#worksummary').hide()

      appendHtmlToTabel(
        tjson.filter((x) => x.所属迭代.indexOf(targetString) > -1)
      )
      replace2Task()
    } else {
      $('.panel-title').html('任务完成汇总表')
      $('#worksummary').show()
    }
  }

  function tableDataJson() {
    var tableData = []
    $('#worksummary tbody tr').each(function () {
      var rowData = {}
      $(this)
        .find('td')
        .each(function (index) {
          //console.log('index',index)
          if (
            $(this).siblings().eq(0).hasClass('w-user') ||
            $(this).hasClass('w-user')
          ) {
            //nothing
          } else if ($(this).parent().children().eq(0).hasClass('text-left')) {
            // console.log('+1', $(this).siblings())
            // console.log('+1', $(this))
            index = index + 1
          } else {
            // console.log('+2')
            // console.log('+2', $(this).siblings())
            // console.log('+2', $(this))
            index = index + 2
          }
          var key = $('#worksummary thead th').eq(index).attr('title')
          var value = $(this).text().trim()
          // console.log('key', key)
          // console.log('value', value)
          rowData[key] = value
        }) // console.log('rowData1', rowData)
      if (!rowData.完成者) {
        rowData.完成者 = tableData[tableData.length - 1].完成者
      }
      if (!rowData.所属迭代) {
        rowData.所属迭代 = tableData[tableData.length - 1]
          ? tableData[tableData.length - 1].所属迭代
          : ''
      } // console.log('rowData2', rowData)
      tableData.push(rowData)
    })
    return tableData
  }

  function tableBugDataJson() {
    var tableData = []
    $('#bugsummary tbody tr').each(function () {
      var rowData = {}
      $(this)
        .find('td')
        .each(function (index) {
          //console.log('index',index)
          if (
            $(this).siblings().eq(0).hasClass('w-user') ||
            $(this).hasClass('w-user')
          ) {
            //nothing
          } else if ($(this).parent().children().eq(0).hasClass('text-left')) {
            // console.log('+1', $(this).siblings())
            // console.log('+1', $(this))
            index = index + 1
          } else {
            // console.log('+2')
            // console.log('+2', $(this).siblings())
            // console.log('+2', $(this))
            index = index + 2
          }
          var key = $('#bugsummary thead th').eq(index).attr('title')
          var value = $(this).text().trim()
          // console.log('key', key)
          // console.log('value', value)
          rowData[key] = value
        }) // console.log('rowData1', rowData)

      if (!rowData.解决者) {
        try {
          rowData.解决者 = tableData[tableData.length - 1].解决者
        } catch (e) {}
      }
      if (!rowData.指派给) {
        try {
          rowData.指派给 = tableData[tableData.length - 1].指派给
        } catch (e) {}
      }

      tableData.push(rowData)
    })

    if (
      location.href.toLowerCase().indexOf('/zentao/report-bugsummary') != -1
    ) {
      //统计tbugjson里每个解决者分别有几条，并拼接字符串
      var solverCount = {}
      tableData.forEach(function (bug) {
        var solver = bug.解决者
        if (solver in solverCount) {
          solverCount[solver]++
        } else {
          solverCount[solver] = 1
        }
      })
      // 将结果转换为字符串形式
      var bugsummaryresult = ''
      for (var solver in solverCount) {
        bugsummaryresult += solver + ': ' + solverCount[solver] + '条； '
      }
      console.log('Bug解决汇总表->&nbsp;' + bugsummaryresult)
      $('.panel-title').html('Bug解决汇总表->&nbsp;' + bugsummaryresult)
    } else if (
      location.href
        .toLowerCase()
        .indexOf('/zentao/report-bugAssignSummary'.toLowerCase()) != -1
    ) {
      //统计tbugjson里每个解决者分别有几条，并拼接字符串
      var solverCount = {}
      tableData.forEach(function (bug) {
        var solver = bug.指派给
        if (solver in solverCount) {
          solverCount[solver]++
        } else {
          solverCount[solver] = 1
        }
      })
      // 将结果转换为字符串形式
      var bugAssignSummaryresult = ''
      for (var solver in solverCount) {
        bugAssignSummaryresult += solver + ': ' + solverCount[solver] + '条； '
      }
      console.log('Bug指派汇总表->&nbsp;' + bugAssignSummaryresult)
      $('.panel-title').html('Bug指派汇总表->&nbsp;' + bugAssignSummaryresult)
    }

    return tableData
  }

  ;('use strict')

  function getDayByDate(day, date) {
    var dates = new Date(date)
    dates.setDate(dates.getDate() + day)

    var year = dates.getFullYear()
    var month = dates.getMonth() + 1
    if (month < 10) {
      month = '0' + month
    }
    var today = dates.getDate()
    if (today < 10) {
      today = '0' + today
    }
    return year + '' + month + '' + today
  }

  function getDay(day) {
    // Date()返回当日的日期和时间。
    var days = new Date() // getTime()返回 1970 年 1 月 1 日至今的毫秒数。
    var gettimes = days.getTime() + 1000 * 60 * 60 * 24 * day // setTime()以毫秒设置 Date 对象。
    days.setTime(gettimes)
    var year = days.getFullYear()
    var month = days.getMonth() + 1
    if (month < 10) {
      month = '0' + month
    }
    var today = days.getDate()
    if (today < 10) {
      today = '0' + today
    }
    return year + '' + month + '' + today
  } // Function to generate a random RGB color

  function getRandomColor() {
    var r = Math.floor(Math.random() * 256)
    var g = Math.floor(Math.random() * 256)
    var b = Math.floor(Math.random() * 256)
    return 'rgb(' + r + ',' + g + ',' + b + ')'
  }

  function replace2Task() {
    let tds = jQuery('td')
    for (let i = 0; i < tds.length; i++) {
      var item = jQuery(tds[i])
      if (isNumberInRange($(item).html())) {
        jQuery(item).html(
          `<a onclick="window.open('/zentao/task-view-` +
            jQuery(item).html() +
            `.html')" style="color:blue;">` +
            jQuery(item).html() +
            `</a>`
        )
      }
    }
  }

  function replace2Bug() {
    let tds = jQuery('td')
    for (let i = 0; i < tds.length; i++) {
      var item = jQuery(tds[i])
      if (isNumberInRange($(item).html())) {
        jQuery(item).html(
          `<a onclick="window.open('/zentao/bug-view-` +
            jQuery(item).html() +
            `.html')" style="color:blue;">` +
            jQuery(item).html() +
            `</a>`
        )
      }
    }
  }

  function filterProjectdeviation() {
    var diedaiLifes = jQuery('#lifetime').val()
    var chanpinIds = jQuery('#product').val()
    var statusIds = jQuery('#status').val()
    var diedaiIdsLife = []
    var diedaiIdsStatus = []
    var diedaiIdsChanpin = []
    diedaiLifes = diedaiLifes
      ? diedaiLifes.filter(function (life) {
          return life // 过滤掉 false 值，包括空字符串、null、undefined、0、false
        })
      : []

    if (diedaiLifes.length > 0) {
      diedaiLifes.forEach(function (life) {
        console.log('diedaiLifes', life) // 在控制台输出每个产品ID
        if (life) {
          jQuery.ajax({
            url: '/zentao/execution-all.html',
            type: 'GET',
            success: function (response2) {
              // console.log('response2',response2)
              var dom2 = $(response2)
              dom2.find('#executionList tbody tr').each(function () {
                // 获取当前行的第五个 td 的文本
                var fifthTdText = jQuery(this).find('td').eq(4).text().trim() // eq(4) 因为索引从 0 开始 // 检查第五个 td 的文本是否等于 'dev'
                if (fifthTdText === life) {
                  // 获取当前行的 data-id 属性并添加到数组中
                  var dataId = jQuery(this).attr('data-id')
                  diedaiIdsLife.push(dataId) // 将 data-id 添加到数组
                }
              })
              //console.log('diedaiIdsLife', diedaiIdsLife)
            },
            error: function (xhr, status, error) {
              console.error(error)
            },
          })
        }
      })
    }
    statusIds = statusIds
      ? statusIds.filter(function (status) {
          return status // 过滤掉 false 值，包括空字符串、null、undefined、0、false
        })
      : []
    if (statusIds.length > 0) {
      statusIds.forEach(function (status) {
        console.log('statusIds', status) // 在控制台输出每个产品ID

        var selectedStatusTexts = $('#status option:selected')
          .map(function () {
            return $(this).text()
          })
          .get()

        jQuery('#executionList tbody tr').each(function (index, trtemp) {
          // 获取当前行的第五个 td 的文本
          var forthTdText = jQuery(trtemp).find('td').eq(3).text().trim() // eq(4) 因为索引从 0 开始 // 检查第五个 td 的文本是否等于 'dev'
          if (selectedStatusTexts.indexOf(forthTdText) > -1) {
            var dataId = jQuery(trtemp).find('td').eq(0).text().trim()
            diedaiIdsStatus.push(dataId) // 将 data-id 添加到数组
          }
        })
      })
    }

    chanpinIds = chanpinIds
      ? chanpinIds.filter(function (id) {
          return id // 过滤掉 false 值，包括空字符串、null、undefined、0、false
        })
      : []
    if (chanpinIds.length > 0) {
      // jQuery('#executionList tbody tr').each(function (idx, tr) {
      //   jQuery(tr).hide()
      // })
      chanpinIds.forEach(function (id) {
        console.log('在控制台输出每个产品ID', id) // 在控制台输出每个产品ID
        if (id) {
          jQuery.ajax({
            url: '/zentao/product-project-all-' + id + '.html',
            type: 'GET',
            success: function (response2) {
              // console.log('response2',response2)
              var dom2 = $(response2)
              var diedaiIdsChanpinTemp = dom2
                .find('#mainContent tbody tr')
                .map(function () {
                  return parseInt($(this).find('td').eq(0).html()).toString()
                })
                .get()
              console.log('diedaiIdsChanpinTemp', diedaiIdsChanpinTemp)
              diedaiIdsChanpin = diedaiIdsChanpin.concat(diedaiIdsChanpinTemp)
            },
            error: function (xhr, status, error) {
              console.error(error)
            },
          })
        }
      })
    } // else { //   jQuery('#executionList tbody tr').each(function (idx, tr) { //     jQuery(tr).show() //   }) // }
    setTimeout(() => {
      // 获取交集
      //console.log('diedaiIdsLife', diedaiIdsLife)
      //console.log('diedaiIdsChanpin', diedaiIdsChanpin)

      var intersectionArray1 = getArrayResult(diedaiIdsLife, diedaiIdsChanpin)
      var intersectionArray = getArrayResult(
        intersectionArray1,
        diedaiIdsStatus
      )
      // console.log('diedaiIdsLife', diedaiIdsLife)
      // console.log('diedaiIdsChanpin', intersectionArray)
      // console.log('diedaiIdsStatus', diedaiIdsStatus)
      // console.log('intersectionArray1', intersectionArray1)
      // console.log('intersectionArray', intersectionArray)
      if (
        (diedaiLifes && diedaiLifes.length > 0) ||
        (chanpinIds && chanpinIds.length > 0) ||
        (statusIds && statusIds.length > 0)
      ) {
        //console.log('diedaiIds3', intersectionArray)
        jQuery('#executionList tbody tr').each(function (idx, tr) {
          jQuery(tr).hide()
        })
        intersectionArray.forEach(function (did) {
          if (did) {
            var intId = parseInt(did)
            jQuery('#executionList tbody tr').each(function (index, trtemp) {
              // console.log('trtemp', trtemp)
              // 获取当前行的第一个td的值
              var firstTdValue = jQuery(trtemp).find('td:first').text().trim() // console.log('firstTdValue',firstTdValue) // console.log('intId.toString()',intId.toString()) // 检查第一个td的值是否等于11
              if (firstTdValue === intId.toString()) {
                jQuery(trtemp).show() // 显示该行
              }
            })
          }
        })
      } else {
        jQuery('#executionList tbody tr').each(function (idx, tr) {
          jQuery(tr).show()
        })
      }

      var totalYuji = 0.0 // 用于存储总和
      var totalShiji = 0.0
      jQuery('#executionList tbody tr:visible').each(function () {
        // 获取当前行的第5个td的值
        var thirdTdValue = jQuery(this).find('td:nth-child(5)').text().trim() // 将其转换为数字并累加

        var numericValue = parseFloat(thirdTdValue) // 检查是否是有效的数字

        if (!isNaN(numericValue)) {
          totalYuji += numericValue
        } // 获取当前行的第5个td的值

        var forthTdValue = jQuery(this).find('td:nth-child(6)').text().trim() // 将其转换为数字并累加

        numericValue = parseFloat(forthTdValue) // 检查是否是有效的数字

        if (!isNaN(numericValue)) {
          totalShiji += numericValue
        }
      })
      var pianCha = (totalShiji - totalYuji).toFixed(1)
      var pianChaLv = ((pianCha * 100) / totalYuji).toFixed(2) + '%'
      var countStr =
        '项目偏差报表---->总预计：' +
        totalYuji.toFixed(1) +
        '；总消耗：' +
        totalShiji.toFixed(1) +
        '；偏差：' +
        pianCha +
        '；偏差率：' +
        pianChaLv
      //console.log('countStr', countStr)
      jQuery('#executionList')
        .parent()
        .parent()
        .find('div.panel-title')
        .html(countStr)
    }, 1000)
  }

  function getArrayResult(array1, array2) {
    //var diedaiLifes = jQuery('#lifetime').val()
    //var chanpinIds = jQuery('#product').val()
    // diedaiLifes = diedaiLifes
    //   ? diedaiLifes.filter(function (life) {
    //       return life // 过滤掉 falsy 值，包括空字符串、null、undefined、0、false
    //     })
    //   : []

    // chanpinIds = chanpinIds
    //   ? chanpinIds.filter(function (id) {
    //       return id // 过滤掉 falsy 值，包括空字符串、null、undefined、0、false
    //     })
    //   : [] // 判断两个数组是否都有值
    if (array1 && array1.length > 0 && array2 && array2.length > 0) {
      console.log('有值0') // 如果都有值，返回交集
      var arraytemp = array1.filter((value) => array2.includes(value))
      arraytemp.push('0') //这里整个有值，免得三个都有值无法交集
      return arraytemp
    } else if (array1 && array1.length > 0) {
      //&& array1.length > 0
      console.log('有值1') // 如果只有 array1 有值，返回 array1
      return array1
    } else if (array2 && array2.length > 0) {
      //&& jQuery('#product').val().length > 0
      console.log('有值2') // 如果只有 array2 有值，返回 array2
      return array2
    } else {
      console.log('无值')
      // 如果两个数组都没有值，返回空数组
      return []
    }
  }

  function isNumberInRange(str) {
    // 使用正则表达式检查字符串是否为数字
    if (!/^\d+$/.test(str)) {
      return false // 如果不是纯数字，则返回false
    } // 将字符串转换为数字进行范围检查

    const num = parseInt(str, 10) // 检查数字是否在999到99999之间

    return num >= 999 && num <= 999999
  }

  jQuery(document).ready(function () {
    if (localStorage.getItem('defaultOrg')) {
      organizeCode = localStorage.getItem('defaultOrg')
    }
    setTimeout(() => {
      tjson = tableDataJson()
      tbugjson = tableBugDataJson()
    }, 2000)

    var url = location.href
    var datenow = getDay(0)
    var datebefore = getDay(-7)
    var dateafter = getDay(7)

    if (url.toLowerCase().indexOf('report-worksummary.html') > -1) {
      // console.log('url1', url)
      // http://myjob.zjshenyue.cn/zentao/report-worksummary-20200701-20200828-3.html
      var worksummarydatestring =
        'report-worksummary-' +
        datebefore +
        '-' +
        datenow +
        '-' +
        organizeCode +
        '-assign.html'
      location.href = url.replace(
        'report-worksummary.html',
        worksummarydatestring
      )
    } else if (url.toLowerCase().indexOf('report-workload.html') > -1) {
      // console.log('url2', url)
      // http://myjob.zjshenyue.cn/zentao/report-workload-20200828-20200904-5-7.0-3-assign.html
      var workloaddatestring =
        'report-workload-' +
        datenow +
        '-' +
        dateafter +
        '-3-7.0-' +
        organizeCode +
        '-assign.html'
      location.href = url.replace('report-workload.html', workloaddatestring)
    } else if (url.toLowerCase().indexOf('report-bugsummary.html') > -1) {
      var bugsummarydatestring =
        'report-bugsummary-' +
        organizeCode +
        '-' +
        datebefore +
        '-' +
        datenow +
        '.html'
      location.href = url.replace(
        'report-bugsummary.html',
        bugsummarydatestring
      )
    } else if (url.toLowerCase().indexOf('zentao/bug-report-') > -1) {
      let checkBoxHtml = `<div class="checkbox-primary"><input type="checkbox" value="bugsOs" id="chartsbugsOs" ><label for="chartsbugsOs">按Bug原因统计</label></div>`
      jQuery('.checkboxes').prepend(checkBoxHtml)
      jQuery('#chartsbugsOs').bind('change', function () {
        if (jQuery('#chartsbugsOs').prop('checked')) {
          localStorage.setItem('checkOs', '1')
        } else {
          localStorage.setItem('checkOs', '0')
        }
      })
      let checkOs = localStorage.getItem('checkOs')
      if (checkOs == '1') {
        jQuery('#chartsbugsOs').prop('checked', true)
      } else if (checkOs == '0') {
        jQuery('#chartsbugsOs').prop('checked', false)
      }
    } else if (
      url.toLowerCase().indexOf('zentao/report-projectdeviation') > -1
    ) {
      jQuery.cookie('pagerExecutionAll', '2000')
      jQuery('#conditions')
        .children()
        .eq(0)
        .removeClass('col-md-3')
        .addClass('col-md-2')
      jQuery('#conditions')
        .children()
        .eq(1)
        .removeClass('col-md-3')
        .addClass('col-md-2') //迭代阶段
      jQuery.ajax({
        url: '/zentao/execution-edit-10.html',
        type: 'GET',
        success: function (response) {
          var dom = $(response)
          var innerHtmls = dom
            .find('#lifetime')
            .parent()
            .map(function () {
              return $(this).html()
            })
            .get()
          console.log('迭代阶段', innerHtmls)

          jQuery('#conditions').append(
            `<div class="w-220px col-md-2 col-sm-6"><div class="input-group"><span class="input-group-addon">迭代类型</span>` +
              innerHtmls +
              `</div></div>`
          )
          jQuery('#lifetime').attr('multiple', true)
          jQuery('#lifetime').removeAttr('onchange')
          jQuery('#lifetime').val([])
          jQuery('#lifetime').trigger('chosen:updated')
          jQuery('#lifetime')
            .chosen({
              no_results_text: '没有找到', // 当检索时没有找到匹配项时显示的提示文本
              disable_search_threshold: 10, // 10 个以下的选择项则不显示检索框
              search_contains: true, // 从任意位置开始检索
            })
            .on('change', function () {
              // 用户改变了选择，快快处理
              console.log('changed')
              console.log($('#lifetime').val())
              jQuery('#lifetime').trigger('chosen:updated') // var diedaiLifes = $('#lifetime').val()
              filterProjectdeviation()
            })

          var innerHtmls = dom
            .find('#status')
            .parent()
            .map(function () {
              return $(this).html()
            })
            .get()
          console.log('迭代状态', innerHtmls)

          jQuery('#conditions').append(
            `<div class="w-220px col-md-2 col-sm-6"><div class="input-group"><span class="input-group-addon">迭代状态</span>` +
              innerHtmls +
              `</div></div>`
          )
          jQuery('#status').attr('multiple', true)
          jQuery('#status').removeAttr('onchange')
          jQuery('#status').val([])
          jQuery('#status').trigger('chosen:updated')
          jQuery('#status')
            .chosen({
              no_results_text: '没有找到', // 当检索时没有找到匹配项时显示的提示文本
              disable_search_threshold: 10, // 10 个以下的选择项则不显示检索框
              search_contains: true, // 从任意位置开始检索
            })
            .on('change', function () {
              // 用户改变了选择，快快处理
              console.log('changed')
              console.log($('#status').val())
              jQuery('#status').trigger('chosen:updated') // var diedaiLifes = $('#lifetime').val()
              filterProjectdeviation()
            })
        },
        error: function (xhr, status, error) {
          console.error(error)
        },
      }) //产品名称

      jQuery.ajax({
        url: '/zentao/report-bugcreate.html',
        type: 'GET',
        success: function (response) {
          var dom = $(response)
          var innerHtmls = dom
            .find('#product')
            .parent()
            .parent()
            .map(function () {
              return $(this).html()
            })
            .get()
          console.log('产品列表', innerHtmls)

          jQuery('#conditions').append(
            `<div class="w-220px col-md-3 col-sm-6">` + innerHtmls + `</div>`
          )
          jQuery('#product').attr('multiple', true)
          jQuery('#product').removeAttr('onchange')
          jQuery('#product')
            .chosen({
              no_results_text: '没有找到', // 当检索时没有找到匹配项时显示的提示文本
              disable_search_threshold: 10, // 10 个以下的选择项则不显示检索框
              search_contains: true, // 从任意位置开始检索
            })
            .on('change', function () {
              // 用户改变了选择，快快处理
              console.log('changed')
              console.log($('#product').val())
              jQuery('#product').trigger('chosen:updated')
              filterProjectdeviation()
            })
        },
        error: function (xhr, status, error) {
          console.error(error)
        },
      })
    } // // if that doesn't work try this // jQuery('#appsBar').html(jQuery('#appsBar').html().replace(/迭代/g, '项目')) // // jQuery('#apps').html(jQuery('#apps').html().replace(/迭代/g,'项目')); // jQuery('#menu').html(jQuery('#menu').html().replace(/迭代/g, '项目'))

    jQuery("#navbar li[data-id='project']").html(
      '<a href="/zentao/report-projectdeviation.html">迭代</a>'
    )
    if (url.toLowerCase().indexOf('zentao/report-worksummary-') > -1) {
      var lastweekHtml = document.createElement('a')
      lastweekHtml.innerHTML = '设置组织'
      lastweekHtml.id = 'defaultOrg'
      lastweekHtml.classList.add('btn')
      lastweekHtml.classList.add('btn-primary')
      lastweekHtml.style.cssText = 'margin-left: 5px' // selectreverseHtml.setAttribute('href', 'javascript:void(0);')
      jQuery('#conditions').find('form').append(lastweekHtml)
      lastweekHtml.addEventListener('click', defaultOrgfn)

      var lastweekHtml = document.createElement('a')
      lastweekHtml.innerHTML = '上一周'
      lastweekHtml.id = 'lastweek'
      lastweekHtml.classList.add('btn')
      lastweekHtml.classList.add('btn-primary')
      lastweekHtml.style.cssText = 'margin-left: 5px' // selectreverseHtml.setAttribute('href', 'javascript:void(0);')
      jQuery('#conditions').find('form').append(lastweekHtml)
      lastweekHtml.addEventListener('click', lastweekfn)

      var nextweekHtml = document.createElement('a')
      nextweekHtml.innerHTML = '下一周'
      nextweekHtml.id = 'nextweek'
      nextweekHtml.classList.add('btn')
      nextweekHtml.classList.add('btn-primary')
      nextweekHtml.style.cssText = 'margin-left: 5px' // selectreverseHtml.setAttribute('href', 'javascript:void(0);')
      jQuery('#conditions').find('form').append(nextweekHtml)
      nextweekHtml.addEventListener('click', nextweekfn)

      var diedaiFilter = document.createElement('div')
      diedaiFilter.innerHTML = `<div class="input-group input-group-sm" style="width: 200px;"><span class="input-group-addon" style="border-radius: 2px 0px 0px 2px; border-left-width: 1px;">所属迭代</span><div class="chosen-container chosen-container-single chosen-compact chosen-highlight-selected chosen-with-search" ><div class="datepicker-wrapper datepicker-date"><input type="text" value="" id="diedaiName" class="form-control form-date"  autocomplete="off" style="border-radius: 0px;"></div></div></div>`
      diedaiFilter.id = 'diedaiFilter'
      diedaiFilter.classList.add('col-sm-3') // diedaiFilter.classList.add('btn-primary')
      diedaiFilter.style.cssText = 'width: 20%' // selectreverseHtml.setAttribute('href', 'javascript:void(0);')
      jQuery('#conditions').find('form').prepend(diedaiFilter)
      jQuery('#diedaiFilter')
        .next()
        .next()
        .removeClass('col-sm-5')
        .addClass('col-sm-4')
      jQuery('#diedaiFilter')
        .next()
        .removeClass('col-sm-3')
        .addClass('col-sm-2')
      jQuery('#diedaiName').change(function () {
        changeDiedai()
      }) //.addEventListener('change', changeDiedai) // jQuery('#conditions').find('form').append('<div class="col-sm-1"><a class="btn btn-primary" id="lastweek" onclick="lastweekfn"> 上一周</a></div>') // jQuery('#conditions').find('form').append('<div class="col-sm-1"><a class="btn btn-primary" id="nextweek" onclick="nextweekfn"> 下一周</a></div>')
    } else if (url.toLowerCase().indexOf('zentao/report-workload-') > -1) {
      var lastweekHtml2 = document.createElement('a')
      lastweekHtml2.innerHTML = '上一周'
      lastweekHtml2.id = 'lastweek2'
      lastweekHtml2.classList.add('btn')
      lastweekHtml2.classList.add('btn-primary')
      lastweekHtml2.style.cssText = 'margin-left: 5px' // selectreverseHtml.setAttribute('href', 'javascript:void(0);')
      jQuery('#conditions').append(lastweekHtml2)
      lastweekHtml2.addEventListener('click', lastweekfn)

      var nextweekHtml2 = document.createElement('a')
      nextweekHtml2.innerHTML = '下一周'
      nextweekHtml2.id = 'nextweek2'
      nextweekHtml2.classList.add('btn')
      nextweekHtml2.classList.add('btn-primary')
      nextweekHtml2.style.cssText = 'margin-left: 5px' // selectreverseHtml.setAttribute('href', 'javascript:void(0);')
      jQuery('#conditions').append(nextweekHtml2)
      nextweekHtml2.addEventListener('click', nextweekfn) // jQuery('#conditions').find('form').append('<div class="col-sm-1"><a class="btn btn-primary" id="lastweek" onclick="lastweekfn"> 上一周</a></div>') // jQuery('#conditions').find('form').append('<div class="col-sm-1"><a class="btn btn-primary" id="nextweek" onclick="nextweekfn"> 下一周</a></div>')
    } else if (url.toLowerCase().indexOf('zentao/task-view-') > -1) {
      jQuery('.detail-content th').each(function () {
        var text = $(this).text()
        if (text == '预计开始') {
          var taskstart = $(this).next().text().trim()
          if (taskstart === '0000-00-00') {
            taskstart = jQuery('.histories-list li')
              .eq(0)
              .text()
              .trim()
              .split(' ')[0]
          }
          localStorage.setItem('taskstart', taskstart + ' 09:00')
        } else if (text == '截止日期') {
          var taskend = $(this).next().text().trim().split('延期')[0].trim()
          if (taskend === '0000-00-00') {
            taskend = jQuery('.histories-list li')
              .eq(0)
              .text()
              .trim()
              .split(' ')[0]
          }
          localStorage.setItem('taskend', taskend + ' 17:30')
        } else if (text == '最初预计') {
          var taskspend = $(this).next().text().trim().replace('工时', '')
          localStorage.setItem('taskspend', taskspend)
        }
      })
    } else if (url.toLowerCase().indexOf('zentao/task-finish-') > -1) {
      jQuery('#realStarted').val(localStorage.getItem('taskstart'))
      jQuery('#finishedDate').val(localStorage.getItem('taskend'))
      jQuery('#currentConsumed').val(localStorage.getItem('taskspend'))
      document
        .querySelectorAll('#currentConsumed')[0]
        .dispatchEvent(new Event('keyup'))
    } else if (url.toLowerCase().indexOf('zentao/task-activate-') > -1) {
      jQuery('#left').val(localStorage.getItem('taskspend'))
    } else if (url.toLowerCase().indexOf('zentao/bug-resolve-') > -1) {
      let bugReasons = `<tr><th>Bug原因</th><td class="w-p35-f required"><select name='os' id='os' class='form-control chosen'><option value='11' title='需求分析-未进行需求评审' data-keys='xuqiufenxi-weijinxingxuqiupingshen xqfxwjxxqps'>需求分析-未进行需求评审</option><option value='99' title='其它' data-keys='qita qt'>其它</option></select></td></tr>`
      jQuery.ajax({
        url: '/zentao/bug-edit-1781.html',
        type: 'GET',
        success: function (response) {
          var dom = $(response)
          var newosList = dom
            .find('#os')
            .parent()
            .parent()
            .map(function () {
              return $(this).html()
            })
            .get(0)
          bugReasons = `<tr>` + newosList + `</tr>`
          jQuery('#mainContent')
            .find('table')
            .find('tr')
            .eq(0)
            .after(bugReasons)
          jQuery('#os').parent().addClass('required w-p35-f')

          var submitBtn = document.getElementById('submit')
          submitBtn.addEventListener('mousedown', mousedownfn)
        },
      })
    } else if (url.toLowerCase().indexOf('zentao/bug-report-') > -1) {
      console.log(url)
      const regex = /bug-report-(\d+)-/
      const match = url.match(regex)

      let htmlTails = '-0-all.html'
      if (url.toLowerCase().indexOf('bysearch') > -1) {
        htmlTails = '-0-bySearch-myQueryID.html'
      }

      if (match && jQuery('#chartsbugsOs').prop('checked')) {
        const number = match[1]
        console.log(number) // Output: 2
        console.log('/zentao/bug-browse-' + number + htmlTails)
        jQuery.ajax({
          url: '/zentao/bug-browse-' + number + htmlTails,
          type: 'GET',
          success: function (response) {
            var dom = $(response)
            var innerHtmls = dom
              .find('td.c-os')
              .map(function () {
                return $(this).html()
              })
              .get() // Count occurrences of each innerHTML

            var counts = {}
            innerHtmls.forEach(function (innerHtml) {
              counts[innerHtml] = (counts[innerHtml] || 0) + 1
            }) // Calculate total count

            var totalCount = innerHtmls.length // Convert counts object to a list of objects with 'key', 'count', 'percent', and 'color'

            var resultList = Object.keys(counts).map(function (key) {
              var count = counts[key]
              var percent = ((count / totalCount) * 100).toFixed(2) + '%'
              var color = getRandomColor()
              let nameStr = key + '：' + count
              return {
                key: key,
                value: count,
                name: nameStr,
                percent: percent,
                color: color,
              }
            }) // Sort the resultList by descending percent

            resultList.sort(function (a, b) {
              return parseFloat(b.percent) - parseFloat(a.percent)
            })

            console.log(resultList)

            let bugOsHtmls = `<div class="table-row chart-row"><div class="main-col"><div class="chart-wrapper text-center"><h4>按Bug原因统计</h4><div class="chart-canvas"><canvas id="chart-bugsPerOs" width="1086" height="304" data-responsive="true" style="width: 1086px; height: 304px;"></canvas></div></div></div><div class="side-col col-xl"><div style="overflow:auto;" class="table-wrapper"><table class="table table-condensed table-hover table-striped table-bordered table-chart" data-chart="pie" data-target="#chart-bugsPerAssignedTo" data-animation="false"><thead><tr><th class="chart-label" colspan="2">条目</th><th class="w-50px text-right">值</th><th class="w-60px text-right">百分比</th></tr></thead>      <tbody id="chart-bugsPerOs-body"></tbody></table></div></div></div>`
            jQuery('div.text-muted').after(bugOsHtmls)
            resultList.forEach(function (item) {
              jQuery('#chart-bugsPerOs-body').append(
                `<tr data-id="0" class=""><td class="chart-color"><i class="chart-color-dot" style="background: ` +
                  item.color +
                  `;"></i></td><td class="chart-label text-left" title="` +
                  item.key +
                  `">` +
                  item.key +
                  `</td><td class="chart-value text-right">` +
                  item.value +
                  `</td><td class="text-right">` +
                  item.percent +
                  `</td></tr>`
              )
            })

            console.log('resultList', resultList) // to draw a pie chart in $('#chart-bugsPerOs') with resultList above
            setTimeout(() => {
              // 基于准备好的dom，初始化echarts实例
              var myChart = echarts.init(
                document.getElementById('chart-bugsPerOs')
              ) // 使用刚指定的配置项和数据显示图表。

              myChart.setOption({
                series: [
                  {
                    color: resultList.map((item) => item.color),
                    name: '',
                    type: 'pie', // 设置图表类型为饼图
                    radius: '55%', // 饼图的半径，外半径为可视区尺寸（容器高宽中较小一项）的 55% 长度。
                    data: resultList,
                  },
                ],
              })
            }, 500)
          },
          error: function (xhr, status, error) {
            console.error(error)
          },
        })
      } else {
        console.log('找不到迭代编号 or 没选择checkbox')
      }
    } //window.open

    if (url.toLowerCase().indexOf('/zentao/report-worksummary') != -1) {
      replace2Task()
    } else if (
      url
        .toLowerCase()
        .indexOf('/zentao/report-workAssignSummary'.toLowerCase()) != -1
    ) {
      replace2Task()
    } else if (url.toLowerCase().indexOf('/zentao/report-bugsummary') != -1) {
      replace2Bug()
    } else if (
      url
        .toLowerCase()
        .indexOf('/zentao/report-bugAssignSummary'.toLowerCase()) != -1
    ) {
      replace2Bug()
    } else if (
      url.toLowerCase().indexOf('/zentao/bug-view-'.toLowerCase()) != -1
    ) {
      jQuery('#legendLife tbody')
        .children()
        .eq(2)
        .children()
        .eq(0)
        .html('责任人')
      //jQuery('th.c-resolvedBy').attr('title', '责任人')
      //jQuery('th.c-resolvedBy a').html('责任人')
    } else if (
      url.toLowerCase().indexOf('/zentao/bug-browse-'.toLowerCase()) != -1
    ) {
      // jQuery('#legendLife tbody')
      //   .children()
      //   .eq(2)
      //   .children()
      //   .eq(0)
      //   .html('责任人')
      jQuery('#bugForm thead th.c-resolvedBy a').html('责任人')

      jQuery('#bugForm thead th.c-pri a').html('客户问题')
      jQuery('#bugForm thead th.c-pri').attr('style', 'width:90px;')
    } else if (
      url.toLowerCase().indexOf('/zentao/execution-bug-'.toLowerCase()) != -1
    ) {
      jQuery('#executionBugForm thead th[title="解决者"]')
        .find('a')
        .html('责任人')
      jQuery('#executionBugForm thead th.c-pri a').html('客户问题')
      jQuery('#executionBugForm thead th.c-pri').attr('style', 'width:90px;')
    } else if (
      url.toLowerCase().indexOf('/zentao/bug-edit-'.toLowerCase()) != -1
    ) {
      jQuery('#resolvedBy').parent().parent().children().eq(0).html('责任人')
    } else if (
      url.toLowerCase().indexOf('zentao/report-projectdeviation') > -1
    ) {
      filterProjectdeviation()
      jQuery("a[title='项目偏差报表']")
        .html('<i class="icon icon-file-text"></i> 迭代偏差报表')
        .attr('title', '迭代偏差报表')
    }
  })
})()
